//
//  QZManagerVC.m
//  map
//
//  Created by 000 on 16/10/8.
//  Copyright © 2016年 faner. All rights reserved.
//

#import "QZManagerVC.h"
#import "BmobSDK/Bmob.h"
//因保存引入
#import <BmobSDK/BmobObject.h>
//#import "BmobSDK/Bmob.h"
//#import <BmobSDK/BmobFile.h>
//#import "QZWGS84TOGCJ02.h"
//#import "constant.h"
//以下为设置大头针及气泡内容引入
#import "QZAnnotation.h"
#import "QZAnnotationView.h"
#import "QZDownView.h"
#import "QZRightPopVC.h"
#import "QZLeftPopVC.h"

#import "QZSetVC.h"
//取消中的
#import "QZCancleVC.h"
@interface QZManagerVC ()<MKMapViewDelegate,CLLocationManagerDelegate,MKMapViewDelegate,QZDownViewDelegate,QZRightPopVCDelegate,QZLeftPopVCDelegate>
{
    CGPoint startPoint;//用于判断长按手势中 开始状态和结束状态的点是否相同
    BOOL isSwitchOn;//用于判断switch开关
    BOOL hadSetFirstP;//是否设置首图
    BOOL hadSetSubT;//是否设置介绍
    BOOL hadSetGoods;//是否设置物品
    BOOL hadDoneDesk;//是否完成了一条完整的任务
    BOOL isSetStart;//是否设置了起始任务
    BOOL isYes;//成立
    NSString *ApinTitle;//大头针标题
    NSString *imageStr;//大头针任务图片
    NSString *ApinSubT;//大头针副标
    NSString *ApinPict;//大头针图片
    
    NSString *alertMessage;//警告信息
    
    int marker;
    NSMutableArray *markerMArray;
    NSMutableArray *detailDeskmArray;

}
@property (nonatomic, strong) CLLocationManager *locationManager;//定位坐标
@property (nonatomic, strong) CLGeocoder *geocoder;//地理编码用
@property (nonatomic, assign) CLLocationCoordinate2D currentCoordinate,deskCoordinate;//获取当前定位坐标（修改后的）
#pragma mark 设置气泡中subtitle
@property (nonatomic, strong) QZDownView *downView;//气泡下方弹出的视图
@property (nonatomic, strong) QZAnnotation *changedAnnotation;
@property (nonatomic, strong) QZRightPopVC *rightPopVC;
@property (nonatomic, strong) QZLeftPopVC *leftPopVC;

#pragma mark xib中的连线
@property (weak, nonatomic) IBOutlet MKMapView *mapView;//地图
@property (weak, nonatomic) IBOutlet UISwitch *sSwitch;
- (IBAction)sSwitchBC:(UISwitch *)sender;//启动点开关
@property (weak, nonatomic) IBOutlet UIButton *setFirstPic;
- (IBAction)setFirstPicBC:(id)sender;//设置首图
@property (weak, nonatomic) IBOutlet UIButton *setSubT;
- (IBAction)setSubTBC:(id)sender;//设置介绍
@property (weak, nonatomic) IBOutlet UIButton *setTitle;
- (IBAction)setTitleBC:(id)sender;//设置物品
@property (weak, nonatomic) IBOutlet UIButton *cancleB;
- (IBAction)cancleBC:(id)sender;//取消设定
@property (weak, nonatomic) IBOutlet UIButton *saveB;
- (IBAction)saveBC:(id)sender;//保存按钮
@property (weak, nonatomic) IBOutlet UIButton *updateB;
- (IBAction)updateBC:(id)sender;
- (IBAction)logoutBC:(id)sender;

@end
static int breakPCount = 0;//断点数

@implementation QZManagerVC

#pragma mark - 懒加载
- (CLLocationManager *)locationManager
{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        //设置代理
        _locationManager.delegate = self;
        //每隔多远定位一次
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        
        [_locationManager startUpdatingLocation];
        //精确度
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        
#if 1
        //-----iOS8.0+需要添加下面的方法才能定位-----//
        
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            //前后台定位授权（必须在Info.plist文件中添加NSLocationAlwaysUsageDescription字段设置显示的授权提示描述 否则无法定位）
            [_locationManager requestAlwaysAuthorization];
            
            //前台定位授权（必须在Info.plist文件中添加NSLocationWhenInUseUsageDescription字段设置显示的授权提示描述 否则无法定位）
            [_locationManager requestWhenInUseAuthorization];
        }
#endif
    }
    return _locationManager;
}
- (CLGeocoder *)geocoder
{
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}
- (QZDownView *)downView
{
    if (_downView == nil) {
        _downView = [QZDownView downViewWithFrame:self.view.bounds];
        _downView.delegate = self;
    }
    return _downView;
}
- (QZRightPopVC *)rightPopVC
{
    if (_rightPopVC == nil) {
        _rightPopVC = [[QZRightPopVC alloc] init];
        _rightPopVC.delegate = self;
    }
    return _rightPopVC;
}
- (QZLeftPopVC *)leftPopVC
{
    if (_leftPopVC == nil) {
        _leftPopVC = [[QZLeftPopVC alloc] init];
        _leftPopVC.delegate = self;
    }
    return _leftPopVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    isSwitchOn = self.sSwitch.on;
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        //如果响应执行下么的方法
        [self.locationManager requestAlwaysAuthorization];
    }
    self.navigationItem.title = @"首页";
    self.navigationItem.hidesBackButton = YES;//隐藏返回按钮
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    [self loadFirstData];
    [self location];
    [self addGesture];
    [self startSet];
    [self defaultSet];
    [self loadSecondData];
}
- (void)startSet
{
    hadSetFirstP=NO;
    hadSetSubT=NO;
    hadSetGoods=NO;
    marker = 101;
}
- (void)defaultSet
{
    isYes = NO;
    isSetStart = NO;
    hadDoneDesk = YES;
    self.setSubT.hidden = YES;
    self.setTitle.hidden = YES;
    self.setFirstPic.hidden = YES;
    self.cancleB.hidden = YES;
    self.updateB.hidden = YES;
}
- (void)loadSecondData
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"annotations"];
    [query orderByAscending:@"createdAt"];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        detailDeskmArray = [NSMutableArray array];
        for (BmobObject *obj in array) {
            QZAnnotation *deskAn = [[QZAnnotation alloc] init];
            deskAn.coordinate = CLLocationCoordinate2DMake([[obj objectForKey:@"latitude"] doubleValue], [[obj objectForKey:@"longitude"] doubleValue]);
            deskAn.title = [obj objectForKey:@"title"];
            deskAn.string1 = [obj objectForKey:@"imageStr"];
            deskAn.subtitle = [obj objectForKey:@"subtitle"];

            [detailDeskmArray addObject:deskAn];
        }
        [self.mapView addAnnotations:detailDeskmArray];
    }];
}
- (void)loadFirstData
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"StartAnnotations"];
    [query orderByAscending:@"createdAt"];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        markerMArray = [NSMutableArray array];
        for (BmobObject *obj in array) {
            QZAnnotation *deskAn = [[QZAnnotation alloc] init];
            deskAn.marker = [obj objectForKey:@"marker"];
            [markerMArray addObject:deskAn.marker];
        }
    }];

}
#pragma mark 添加手势
- (void)addGesture
{
    UILongPressGestureRecognizer *longPressGS = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressClick:)];
    [self.mapView addGestureRecognizer:longPressGS];
}
#pragma mark 长按手势
- (void)longPressClick:(UIGestureRecognizer *)gestureReconizer
{
    
    if (gestureReconizer.state == UIGestureRecognizerStateBegan) {
        //坐标转换
        CGPoint point = [gestureReconizer locationInView:self.mapView];
        startPoint = point;
    } else if (gestureReconizer.state == UIGestureRecognizerStateEnded) {
        //坐标转换
        CGPoint point = [gestureReconizer locationInView:self.mapView];
        if (startPoint.x == point.x &&startPoint.y == point.y) {
            if (!isSwitchOn) {
                if (hadDoneDesk==YES) {
                    alertMessage= @"您还没设置起始点";
                    [self alertView];
                } else{
                    isYes = YES;
                }
            } else if (isSwitchOn){
                if (isSetStart&&!hadDoneDesk) {
                    alertMessage=@"您已设置起始点";
                    [self alertView];
                } else {
                    isYes = YES;
                }
            }
            
            if (isYes == YES) {
                //2.将触摸点转化为经纬度
                CLLocationCoordinate2D coordinate = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
                QZAnnotation *annotation = [[QZAnnotation alloc] init];
                annotation.coordinate = coordinate;
                annotation.title = @"你好";
                annotation.subtitle = @"完成任务";
                annotation.string = @"add";
                self.deskCoordinate = coordinate;
                self.saveB.hidden = NO;
                self.saveB.userInteractionEnabled = YES;
                [self.mapView addAnnotation:annotation];
                [self settingBtnChange];//设置的那些按钮出现
                
            }
        }
}
}
//长按后到反应
- (void)settingBtnChange
{
    self.setSubT.hidden = NO;
    self.setTitle.hidden = NO;
    self.setFirstPic.hidden = NO;
    self.updateB.hidden = NO;
    isYes = NO;
}
#pragma mark 制作大头针
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    //如果是当前位置就设置为nil
    if (annotation == mapView.userLocation) {
        return nil;
    }else{
        QZAnnotation *myAnnotation = [[QZAnnotation alloc] init];
        myAnnotation = annotation;
        QZAnnotationView *myAnnotationView = [QZAnnotationView getQZAnnotationViewWithMapView:mapView andAnnotation:annotation];
//        myAnnotationView.delegate = self;
        myAnnotationView.image = [UIImage imageNamed:@"desk"];
        myAnnotationView.canShowCallout = NO;
        return myAnnotationView;
    }
    
}

- (void)downView:(QZDownView *)downView didDeterMineBtnClickWithText:(NSString *)text andI:(int)i
{

    ApinSubT = text;
    hadSetSubT = YES;
    self.setSubT.hidden = YES;
}


- (void)downBtnClick
{
    [self.downView show];
}

- (void)leftBtnClick
{
    [self presentViewController:self.leftPopVC animated:YES completion:nil];
}
- (void)leftPopVC:(QZLeftPopVC *)leftPopVC didQuedingBtnClickWithImage:(UIImage *)image andI:(int)i
{
    NSData *imaData =UIImageJPEGRepresentation(image, 0.3);
    NSString *photoString = [imaData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    ApinPict = photoString;
    hadSetFirstP = YES;
    self.setFirstPic.hidden=YES;
}

- (void)rightBtnClick
{
    [self presentViewController:self.rightPopVC animated:YES completion:nil];
}
- (void)rightPopVC:(QZRightPopVC *)rightPopVC didDetermineBtnClickWithI:(int)i
{
    ApinTitle = self.rightPopVC.selecteText;
    imageStr = self.rightPopVC.imageStr;
    hadSetGoods = YES;
    self.setTitle.hidden = YES;
}
#pragma mark 跟踪自己的位置
- (void)location
{
    MKCoordinateSpan span = MKCoordinateSpanMake(0.026416, 0.019511);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.currentCoordinate, span);
    [self.mapView setRegion:region animated:YES];
    //显示用户的位置
    self.mapView.showsUserLocation = YES;
//    self.mapView.mapType = MKMapTypeStandard;
    //追踪用户的位置
    self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}
#pragma mark - xib中的方法实现
- (IBAction)sSwitchBC:(UISwitch *)sender {
    if (sender.isOn) {
        isSwitchOn = YES;
    } else {
        isSwitchOn = NO;
    }
    
    if (isSwitchOn&&breakPCount!=0) {
        
        BmobObject *breakPObject = [BmobObject objectWithClassName:@"breakPoints"];

        
        NSString *breakPointC = [NSString stringWithFormat:@"%d",breakPCount];
        [breakPObject setObject:breakPointC forKey:@"breakPointCount"];
        
        [breakPObject saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {
                breakPCount = 0;
                self.cancleB.hidden = NO;
                
                hadDoneDesk = YES;
                isSetStart = NO;

                
            } else {
                alertMessage = @"breakPoints保存失败";
                [self alertView];
            }
        }];
    }
}
- (IBAction)setFirstPicBC:(id)sender {
    [self leftBtnClick];
}
- (IBAction)setSubTBC:(id)sender {//设置副标
    [self.downView show];
}
- (IBAction)setTitleBC:(id)sender {//设置标题
    [self rightBtnClick];
}
- (IBAction)cancleBC:(id)sender {
    if (isSwitchOn&&hadDoneDesk) {
        QZCancleVC *cancleVC = [[QZCancleVC alloc] init];
        [self presentViewController:cancleVC animated:YES completion:nil];
    } else {
        alertMessage = @"您有未保存任务";
        [self alertView];
    }
    
}
- (IBAction)updateBC:(id)sender {
    [self.mapView removeAnnotations:self.mapView.annotations];
    self.setTitle.hidden = YES;
    self.setFirstPic.hidden = YES;
    self.setSubT.hidden = YES;
    self.saveB.hidden = YES;
    [self loadSecondData];
}

- (IBAction)logoutBC:(id)sender {
    QZSetVC *setVC = [[QZSetVC alloc] init];
    [self presentViewController:setVC animated:YES completion:nil];
    
}
- (IBAction)saveBC:(id)sender {
    
    self.saveB.enabled = NO;
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(saveData:) object:self.saveB];
    [self performSelector:@selector(saveData:) withObject:self.saveB afterDelay:0.2f];
}
#pragma mark 保存系列
- (void)saveData:(UIViewController *)vc
{
    if (hadSetGoods&&hadSetFirstP&&hadSetSubT) {
        [self saveApinTable];
        [self startSet];
    } else {
        if (!hadSetSubT) {
            alertMessage = @"副标题未设置";
        } else if (!hadSetFirstP){
            alertMessage = @"首图未设置";
        } else if(!hadSetGoods) {
            alertMessage = @"标题为设置";
        }
        [self alertView];
        self.saveB.enabled = YES;
    }
}

#pragma mark 保存长按后的大头针
- (void)saveApinTable
{
    QZAnnotation *annotation = [[QZAnnotation alloc] init];
    annotation.coordinate = self.deskCoordinate;
    if (isSwitchOn) {
        NSString *lastMarkStr = markerMArray.lastObject;
        int lastMarker = [lastMarkStr intValue];
        NSString *markerStr = [NSString stringWithFormat:@"%d",marker-100+lastMarker];
        BmobObject *startObject = [BmobObject objectWithClassName:@"StartAnnotations"];
        
        [startObject setObject:@(self.deskCoordinate.latitude) forKey:@"latitude"];
        [startObject setObject:@(self.deskCoordinate.longitude) forKey:@"longitude"];
        [startObject setObject:ApinTitle forKey:@"title"];//标题
        [startObject setObject:ApinSubT forKey:@"subtitle"];//副标
        [startObject setObject:ApinPict forKey:@"imageStr"];//相册图标
        [startObject setObject:markerStr forKey:@"marker"];//任务标记
        
        NSString *lineName = @"任务";
        [startObject setObject:lineName forKey:@"lineName"];
        [startObject saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {
                marker++;
                self.saveB.hidden = YES;
                self.saveB.enabled = YES;
                self.saveB.userInteractionEnabled = NO;
                self.updateB.hidden = YES;
                hadDoneDesk = NO;
                isSetStart = YES;
                
//                [self nameArrayAddData];
            }else{
                self.saveB.enabled = YES;
                alertMessage = @"保存开启失败";
                [self alertView];
            }
        }];

    }
    BmobObject *AnObject = [BmobObject objectWithClassName:@"annotations"];
    [AnObject setObject:@(self.deskCoordinate.latitude) forKey:@"latitude"];
    [AnObject setObject:@(self.deskCoordinate.longitude) forKey:@"longitude"];

    [AnObject setObject:ApinTitle forKey:@"title"];//标题
    [AnObject setObject:ApinSubT forKey:@"subtitle"];//副标
    [AnObject setObject:ApinPict forKey:@"imageStr"];//相册图标
    [AnObject setObject:imageStr forKey:@"deskImStr"];
    
    [AnObject saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            [self updataSuccess];
            
        }else{
            self.saveB.enabled = YES;
            alertMessage = @"保存失败";
            [self alertView];
        }
    }];
}
- (void)updataSuccess
{
    self.saveB.hidden = YES;
    self.saveB.enabled = YES;
    self.saveB.userInteractionEnabled = NO;
    breakPCount++;
}
#pragma mark - 读取数据方法

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    self.currentCoordinate = userLocation.coordinate;
}
#pragma mark - CLLocationManagerDelegate
#pragma mark 自己位置的代理方法
//-----------------------时时定位－－－－－－－－－－－－－－－－－－－－－－－－－－－－
//CLLocationManager委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //得到newLocation
    CLLocation *loc = [locations objectAtIndex:0];
    //判断是不是属于国内范围
//    if (![QZWGS84TOGCJ02 isLocationOutOfChina:[loc coordinate]]) {
//        //转换后的coord
//        CLLocationCoordinate2D coord = [QZWGS84TOGCJ02 transformFromWGSToGCJ:[loc coordinate]];
//    }else{
//    }
}

- (void)alertView
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:alertMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

@end
